using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using IGlobalist.Cms.Model;
using NVelocityTemplateEngine;
using NVelocityTemplateEngine.Engines;
using NVelocityTemplateEngine.Interfaces;

namespace IGlobalist.Cms.Presentation
{
    public class NVelocityTemplateEngine : ITemplateEngine
    {
        private ITemplate _Template;
        private NVelocityMemoryEngine _Engine;
        private IDictionary _Context = new Hashtable();
        public NVelocityTemplateEngine(ITemplate template)
        {
            if (template.Type != TemplateType.NVelocity)
                throw new Exception("[NVelocity] Template type not match.");

            this._Engine = (NVelocityMemoryEngine) NVelocityEngineFactory.CreateNVelocityMemoryEngine(true);
           
            Commons.Collections.ExtendedProperties props = new Commons.Collections.ExtendedProperties();            
            props.AddProperty("velocimacro.permissions.allow.inline",true);             
            props.AddProperty("velocimacro.permissions.allow.inline.to.replace.global", false);
            props.AddProperty("velocimacro.permissions.allow.inline.local.scope", true);
            props.AddProperty("velocimacro.context.localscope", true);
            this._Engine.Init(props);
            
            this._Template = template;
        }


        #region ITemplateEngine Members

        public ITemplate Template
        {
            get
            {
                return this._Template;
            }
        }

        public void AddToContext(string key, object obj)
        {
            this._Context.Add(key, obj);
        }

        public void Render(System.IO.TextWriter output)
        {
            this._Engine.Process(_Context, output, _Template.TemplateContent);            
        }
        #endregion
    }
}
